<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小懒隔空充电</title>
    <link href="../img/logo.ico" rel="icon" type="image/x-ico">
    <link rel="stylesheet" href="../css/c-theme.css">
    <!-- <style>
        div {
            /*border: 1px solid #000;*/
        }

        html, body {
            text-align: center;
            width: 100%;
            height: 100%;
        }

        #box {
            width: 76%;
            height: 100%;
            margin: 0 auto;
        }

        #sketchpad {
            width: 60%;
            height: 100%;
            float: left;
            position: relative;
        }

        #parent {
            position: relative;
            float: left;
            width: 100%;
            height: 100%;
            background: #ffffff;
        }

        #children {
            position: absolute;
            width: 100px;
            height: 100px;

            bottom: 45%;
            right: 45%;

            background-color: antiquewhite;
            cursor: move;
        }

        .icon {
            float: left;
            border: 2px solid gray;
            width: 180px;
            height: 70px;
            line-height: 70px;
            text-align: left;
            margin-bottom: 20px;
            margin-left: 20px;
            margin-top: 20px;
            font-size: 22px;
            padding-left: 10px;
            padding-right: 15px;
        }

        #head {
            width: 100%;
            height: 100px;
        }

        #title {
            color: red;
            line-height: 150px;
            float: left;
        }

        #logo {
            width: 100%;
            height: 100px;
            float: left;
            text-align: left;
        }

        .butDiv {
            width: 100%;
            height: 100px;
            float: left;
            text-align: left;
            line-height: 170px;
        }
    </style> -->
    <link rel="stylesheet" href="../css/jquery-ui.css">
    <!-- <link rel="stylesheet" href="../css/style.css"> -->
    <script src="../js/jquery-3.1.1.min.js"></script>
    <script src="../js/jquery-ui.js"></script>
</head>
<body>
    <div id="box">
        <div id="head">
            <div id="logo">
                <img src="../img/logo.jpg">
            </div>
            <div class="title">
                <h2 id="title"></h2>
            </div>
        </div>
        <div class="con">
            <div id="sketchpad">
                <div id="parent">
                    <div id="children" class="ui-widget-content"
                         style="background-image: url(../img/ewm.png);background-size: cover;">
                        <div id="d_color">
                            <p>A467158B46D5</p>
                        </div>
                    </div>
                    <img id="back_img" style="display:none" alt="隐藏图片"/>
                    <img id="back_img1" style="display:none" alt="隐藏图片"/>
                </div>
                <div class="l-tip">
                    拖动二维码边可以调整大小和位置<br>
                    流程：上传背景图->上传设备码->拖动选择二维码位置和尺寸->点击生成贴纸->下载贴纸(<b style="color:red">有效期30分钟</b>)
                </div>
            </div>
            <div class="action">
                <div class="action-box">
                    <div class="but-action">
                        <div class="icon" onclick="clinkBackImg('backImg')">
                            <img src="../img/imgIcon.png" alt="图片图标">
                            <p>上传背景图</p>
                            <input type="file" id="backImg" accept=".jpg, .png" style="display: none">
                        </div>
                        <span id="fileName1" style="font-size: 10px">未上传</span>
                    </div>
                    <div class="but-action">
                        <div class="icon" onclick="clinkBackImg('devicesFile')">
                            <img src="../img/upload.png" alt="图片图标">
                            <input type="file" id="devicesFile" accept=".xls, .xlsx, .cvs" style="display: none">
                            <p style="float: right">上传设备码</p>
                        </div>
                        <span id="fileName2" style="font-size: 10px">未上传</span>
                    </div>
                    <a href="../template/模板.xlsx" download="模板.xlsx">下载设备码表格样式</a>

                    <div class="key-edit">
                        编码颜色：<input type="color" id="fontColor" onchange="updateColor()"/>
                        编码大小：<input type="number" value="10" id="fontSize" style="width: 40px;" onchange="updateSize()"/>
                    </div>

                    <div id="btn-create" class="but-action but-disabled">
                        <div class="icon" onclick="widthHeight()">
                            <img src="../img/export.png" alt="导入图标">
                            <p style="float: right">批量生成</p>
                        </div>
                    </div>
                    <div id="btn-download" class="but-action but-disabled">
                        <div class="icon" onclick="download()">
                            <img src="../img/upload1.png" alt="导出图标">
                            <p style="float: right">批量下载</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div id="footer">小懒隔空充电 @2016-2025</div>
    </div>
</body>
<script>
    let type = 1;
    let uploadBg = false;
    let uploadKey = false;
    $(function () {
        type = getUrlParam('type');
        if (type == "2") {
            //无线充电器
            $("#title").html("蓝牙款无线充")
        } else {
            $("#title").html("wifi款无线充")
        }
        $("#children").resizable({containment: '#parent', aspectRatio: 1 / 1,});
        $("#children").draggable({containment: '#parent'});
        $("#backImg").change(function (e) {
            let imgBox = e.target;
            if(uploadImg($('#backImg'), imgBox)){
                setTimeout(function () {
                    setBackImg(imgBox.files[0]);
                }, 500);
                uploadBg = true;
                canCreate();
            }
        });
        $("#devicesFile").change(function (e) {
            let imgBox = e.target;
            let file = imgBox.files[0];
            $("#fileName2").html(text(file.name));
            uploadKey = true;
            canCreate();
        });

        function canCreate(){
            if (uploadBg && uploadKey) {
                $("#btn-create").removeClass("but-disabled");
            }
        }

        function uploadImg(element, tag) {
            let file = tag.files[0];
            $("#fileName1").html(text(file.name));
            if (!/image\/\w+/.test(file.type)) {
                alert("看清楚，这个需要图片！");
                return false;
            }
            setNoneBack(file);
            return true;
        }

        function text(text) {
            let split = text.split(".");
            text = split[0];
            let result = "";//处理结果
            let count = 0;
            let displayLength = 10;
            for (let i = 0; i < displayLength; i++) {
                let _char = text.charAt(i);
                if (count >= displayLength) break;
                if (/[^x00-xff]/.test(_char)) count++; //双字节字符，//[u4e00-u9fa5]中文
                result += _char;
                count++;
            }
            if (result.length < text.length) {
                result += "...";
            }
            return result + "." + split[1];
        }

        function setNoneBack(file) {
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function () {
                let imgSrc = this.result;
                $("#back_img1").attr('src', imgSrc);
            }
        }

        function setBackImg(file) {
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function () {
                let imgSrc = this.result;
                // let p = $("#parent");
                // //图片实际上的宽
                // let width = $("#back_img1").width();
                // //图片实际上的高
                // let height = $("#back_img1").height();
                // //div宽
                // let divWidth = p.width();
                // let ratio = width / divWidth;
                // $("#box").css("height",(height/ratio)/0.85);

                //设置背景图片
                // p.css("background-image", "url(" + imgSrc + ")");
                // p.css("background-repeat", " no-repeat");

                // let number = height / ratio;
                // if (number > divHeight) {
                // p.css("background-size", "100% auto");
                // } else {
                //     p.css("background-size", "100% auto");
                // }

                $("#back_img").attr('src', imgSrc);
                $("#back_img").css('display', "block");

            };
        }

        function getUrlParam(name) {
            let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            let r = window.location.search.substr(1).match(reg);  //匹配目标参数
            if (r != null) return unescape(r[2]);
            return null; //返回参数值
        }
    });

    function clinkBackImg(id) {
        let backImg = document.getElementById(id);
        backImg.click();
    }

    function updateSize() {
        let val = $("#fontSize").val();
        $("#d_color").css("font-size", val + "px");
    }

    function updateColor() {
        let val = $("#fontColor").val();
        $("#d_color").css("color", val);
    }

    let name = '';
    let create = false;

    //批量生成
    function widthHeight() {
        if(name!==""){
            $.ajax({
                url: '/generated/deleteByName',
                type: 'post',
                data: {"name":name},
                success: function (data) {
                }
            });
        }
        if (create) {
            alert("已开始批量生成，请勿重复点击！");
            return;
        }
        create = true;
        
        //二维码竖
        let top = $('#children').position().top;
        //二维码横
        let left = $('#children').position().left;
        //二维码宽
        let ewmWidth = $('#children').width();
        //二维码高
        let ewmHeight = $('#children').height();
        //图片展示出来的宽
        let imgWidth = $("#back_img").width();
        let formData = new FormData();
        //背景图片
        let file = $("#backImg")[0].files[0];
        let file1 = $("#devicesFile")[0].files[0];
        if (file == null || file1 == null) {
            alert("未设置背景图片或设备码！");
            create = false;
            return;
        }
        formData.append("imgFile", file);
        //设备码文件
        formData.append("file", file1);
        //编码颜色
        let val = $("#fontColor").val();
        if (val === "") {
            val = "#000000FF"
        }
        let color = val.replace("#", "");
        formData.append("rgb", rgb(color));

        //图片展示出来的宽
        formData.append("imgWidth", imgWidth);
        formData.append("ewmWidth", ewmWidth);
        formData.append("ewmHeight", ewmHeight);
        formData.append("top", top);
        formData.append("left", left);
        formData.append("fontSize", $("#fontSize").val());

        //设备类型
        formData.append("type", type);

        alert("开始批量生成！请耐心等待弹窗提示后下载");
        $.ajax({
            url: '/generated/batch',
            type: 'post',
            data: formData,
            // 告诉jQuery不要去设置Content-Type请求头

            contentType: false,
            // 告诉jQuery不要去处理发送的数据
            processData: false,
            success: function (data) {
                name = data;
                create = false;
                $("#btn-download").removeClass("but-disabled");
                alert("生成成功！有效期30分钟，请及时下载");
            }
        });
    }

    function rgb(str) {
        // 输入参数格式 如： 'F30A09'; 输出格式 如：(255,10,9)
        let res = [];
        for (let i = 0; i < str.length; i = i + 2) {
            res.push(Number('0x' + str.substr(i, 2)))
        }
        return res.join(',');
    }

    function download() {
        if (name == null || name === '') {
            alert("文件不存在，请先生成文件！");
            return;
        }
        $.ajax({
            url: '/generated/getDomainName',
            type: 'get',
            success: function (data) {
                window.location.href = 'http://'+data+'/generated/download?name=' + name;
                name = '';
            }
        });
        // window.location.href = 'http://''/generated/download?name=' + name;
        // window.location.href = 'http://localhost:9090/generated/download?name=' + name;
    }

</script>

</html>